"ui";
engines.all().map((ScriptEngine) => {
  if (engines.myEngine().toString() !== ScriptEngine.toString()) {
    ScriptEngine.forceStop();
  }
});

let yashuUtil = require("./yashuUtil");
let service = require("./service");
let config = require("./config");
let baseUrl = config.baseUrl;
let themeColor = config.themeColor;
let status_bar_height = yashuUtil.status_bar_height;

ui.layout(
  <vertical bg="{{themeColor}}" paddingTop="{{status_bar_height}}px" gravity="center">
    <text
      w="*"
      gravity="center"
      layout_gravity="bottom"
      text="私人令牌"
      layout_width="wrap_content"
      layout_height="wrap_content"
      textSize="32"
      textColor="#ffffff"
      textStyle="bold"
    />
    <input
      padding="16"
      gravity="center"
      textSize="16sp"
      id="token"
      textColor="#ffffff"
      hint="码云/ 右上角/ 设置/ 安全设置/ 私人令牌"
    ></input>
    <text
      id="login"
      w="200dp"
      text="登录"
      textColor="#ffffff"
      padding="20"
      gravity="center"
      marginTop="32dp"
      textSize="22sp"
    />
    <text id="warn" w="300dp" textColor="#ffffff" padding="20" gravity="center" marginTop="32dp" textSize="22sp" />
  </vertical>
);
let warnContent = "token是超级密码, 拥有最高权限, 泄露可能有严重后果, 请谨慎操作!";
ui.warn.setText(warnContent);
ui.login.click(function () {
  let storage = config.storage;
  let token = ui.token.text().trim();
  if (!token) {
    toastLog("请填写 私人令牌");
  } else {
    let url = baseUrl + "/user?access_token=" + token;
    http.get(url, {}, function (res, err) {
      if (err) {
        console.error(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("私人令牌错误");
      } else {
        let data = res.body.json();
        let name = data.name;
        toastLog("欢迎回来, " + name);
        service.writeToken(token);
        storage.put("userInfo", data);
        engines.execScriptFile("./page/user.js");
      }
    });
  }
});
yashuUtil.setStatusBarFullTransparent();
yashuUtil.setBackgroundRoundGradientCornerRadii(ui.token, "#229c27b0");
yashuUtil.setBackgroundRoundGradientCornerRadiiButton(ui.login, "#1fa62b");
ui.token.setHintTextColor(colors.parseColor("#b3ffffff"));
/* -------------------------------------------------------------------------- */
